package com.atguigu;


import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

//leetcoke第一题

public class T3 {
    public static int[] twoSums(int[] arr, int target) {
        int[] a = {0, 0};
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] + arr[j] == target) {
                    a[0] = i;
                    a[1] = j;
                    return a;
                }
            }
        }
        return null;
    }

    public static int[] twoSums1(int[] arr, int target){
        Map<Integer,Integer> map = new HashMap<>(arr.length);
        for (int i = 0; i < arr.length; i++) {
            int partnerNumber = target - arr[i];
            if (map.containsKey(partnerNumber)){//检测映射中是否存在指定的键，返回一个布尔值
                return new int[]{map.get(partnerNumber),i};//map.get是通过key取v
            }
            map.put(arr[i],i);//存入hash表
        }
        return null;
    }

    public static void main(String[] args) {
        int[] arrays = {2, 7, 8};
        int target = 9;
        System.out.println(Arrays.toString(twoSums1(arrays, target)));
    }
}

